import { NextRequest, NextResponse } from "next/server"
import * as jose from "jose"

export const JWT_SECRET = "i"

// 验证 JWT
export async function verifyJwtToken(token: string) {
  const secret = new TextEncoder().encode(JWT_SECRET)
  try {
    const { payload } = await jose.jwtVerify(token, secret)
    return payload
  } catch (error) {
    console.error("Invalid token:", error)
    throw error
  }
}

export async function middleware(request: NextRequest) {
  // console.log("进入鉴权")

  const token = request.headers.get("Authorization")?.split(" ")[1]
  if (!token) {
    return NextResponse.json(
      { error: "None token", status: 401 },
      { status: 401 } // 修正状态码为401
    )
  }
  try {
    const verified = await verifyJwtToken(token)
    if (!verified) {
      return NextResponse.json(
        { error: "Invalid token", status: 401 },
        { status: 401 } // 修正状态码为401
      )
    }
    // 将用户信息添加到请求头中
    const requestHeaders = new Headers(request.headers)
    requestHeaders.set("user", JSON.stringify(verified))

    // 检查并设置 x-Request-Id 头
    const requestId = request.headers.get("x-request-Id")
    if (requestId) {
      requestHeaders.set("x-Request-Id", requestId)
    }

    return NextResponse.next({
      request: {
        headers: requestHeaders,
      },
    })
  } catch (error) {
    return NextResponse.json(
      { error: "登录过期", status: 401 },
      { status: 401 } // 修正状态码为401
    )
  }
}

// 配置需要进行中间件验证的路径
// todo 这里匹配有问题
export const config = {
  matcher: ["/api/auth/:path*"],
}
